package com.yuan.yblog.portal.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuan.yblog.crud.entity.Role;
import com.yuan.yblog.crud.entity.UserRole;
import com.yuan.yblog.crud.service.IRoleService;
import com.yuan.yblog.crud.service.IUserRoleService;
import com.yuan.yblog.crud.service.IUserService;
import com.yuan.yblog.security.pojo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hepeiyuan on 2024/6/3 20:48
 * @description 权限服务类
 */
@Service
public class AuthorityService {

    @Autowired
    IUserRoleService iUserRoleService;

    @Autowired
    IRoleService iRoleService;

    /**
     * 获取用户权限信息
     * @param userId 用户id
     */
    public HashSet<SimpleGrantedAuthority> getUserAuthorities(long userId) {
        // 查询权限
        List<UserRole> userRoleList = iUserRoleService.getBaseMapper().selectList(new QueryWrapper<UserRole>().eq("user_id",userId));
        HashSet<SimpleGrantedAuthority> authorities = new HashSet<>();
        if (!userRoleList.isEmpty()) {
            List<Long> roleIds = userRoleList.stream().map(UserRole::getRoleId).toList();
            List<Role> roles = new ArrayList<>();
            for (Long roleId : roleIds) {
                roles.add(iRoleService.selectByIdAndBuildCache(roleId));
            }
            for (Role role : roles) {
                authorities.add(new SimpleGrantedAuthority(role.getRoleKey()));
            }
        }
        // 返回结果
        return authorities;
    }
}
